package com.ny.zmb.openapi.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ny.zmb.openapi.util.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 支付宝实名认证
 */
public class AliAuthDemo {
    private static final String ALLCHAR = "0123456789ABCDEF";

    /**
     * 发起方商户号 服务商在银盛给自己开设的商户号，即可当作发起方商户号
     * 生产环境需要使用自己的发起发商户号，并找相应的对接人员开通所需要的接口权限，并告知是国密还是RSA
     */
    private static final String CERT_ID = "826440345119153";

    /**
     * 银盛端公钥证书
     * 生产环境需要自行去开放平台上下载银盛公钥证书，也可以找对接人提供
     */
    private static final String YS_PUBLIC_CER_PATH = "D:/datas/SHA-test/service.cer";

    /**
     * 商户端的私钥证书
     * 生产环境需要使用自己生产的私钥证书
     */
    private static final String MERC_PRIVATE_FILE = "D:/datas/SHA-test/826440345119153/client.pfx";

    /**
     * 商户端私钥证书密码
     * 生产环境需要使用自己私钥的密码
     */
    private static final String MERC_PRIVATE_FILE_PASSWORD = "123456";

    /**
     * 请求地址域名
     */
    private static final String HTTP_NET = "https://appdev.ysepay.com";
    //测试 https://appdev.ysepay.com
    //生产 https://ysgate.ysepay.com

    public static void main(String[] args) throws Exception {
        /** 0、文件上传*/
        uploadDocument();

        /** 1、支付宝实名认证申请*/
        //aliAuthSubmit();

        /** 2、支付宝实名认证撤销*/
        //cancelAuthMessages();

        /** 3、支付宝实名认证申请单状态查询*/
        //getAuthMessagesByApplyNo();

        /** 4、支付宝实名认证申请单状态查询*/
        //getAuthState();
    }

    /**
     * 文件上传demo
     */
    public static void uploadDocument() throws Exception {
        String HTTP_URL = HTTP_NET + "/openapi/file/report/uploadDocument";

        File file = new File("C:\\Users\\MI\\Downloads\\test.png");

        /** 1、封装请求参数，bizContent（业务参数，需要加密）和check（需要生成密钥并加密）后面设置值*/
        Map<String, String> reqMap = new HashMap<String, String>();
        //接口方法名，根据接口文档取值
        reqMap.put("method", "file.report.uploadDocument");
        //请求时间
        reqMap.put("timeStamp", getCurrentDateTime("yyyy-MM-dd HH:mm:dd"));
        //固定utf-8
        reqMap.put("charset", "utf-8");
        //请求流水号
        reqMap.put("reqId", String.valueOf(System.currentTimeMillis()));
        //发起方商户号，服务商在银盛给自己开设的商户号，即可当作发起方商户号，由银盛生成并下发。 注意：不同于子商户号，服务商发展的商户即为子商户号
        reqMap.put("certId", CERT_ID);
        //版本号，默认1.0，按接口文档来
        reqMap.put("version", "1.0");

        /** 2、生成对业务参数加密的密钥*/
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
        }
        String key = ByteUtil.toHexString(sb.toString());

        /** 3、使用银盛公钥对密钥key进行加密，得到加密的key并设置到请求参数check中。publicFilePath为存放银盛公钥的地址*/
        byte[] byte1= RSA256Util.encrypt(YS_PUBLIC_CER_PATH, ByteUtil.hexStringToBytes(key));
        String check = Base64.encodeBase64String(byte1);
        //加密后的密钥
        reqMap.put("check", check);

        /** 4、封装业务参数,具体参数见文档，这里只是举例子*/
        Map<String, Object> bizContentMap = new HashMap<>();
        //meta媒体文件元素信息
        Map<String, String> metaJSONObject = new HashMap<>();
        FileInputStream fileInputStream = new FileInputStream(file);
        String sha256 = DigestUtils.sha256Hex(fileInputStream);
        metaJSONObject.put("sha256", sha256);
        //上传文件类型,上传文件类型，支持pdf、excel等文件，注意：必须与文件类型一致，否则会导致上传文件无效
        metaJSONObject.put("fileType", "png");
        //图片名称
        metaJSONObject.put("fileName", "test");
        //设置媒体元素信息
        bizContentMap.put("meta", metaJSONObject);

        /** 5、使用生成的密钥key对业务参数进行加密，并将加密后的业务参数放入请求参数bizContent中*/
        byte[] bte = AESUtil.encrypt(JSONObject.toJSONBytes(bizContentMap, SerializerFeature.WriteNullStringAsEmpty), ByteUtil.hexStringToBytes(key));
        String msgBizContent = Base64.encodeBase64String(bte);
        reqMap.put("bizContent", msgBizContent);

        /** 6、将请求参数进行sort排序，生成拼接的字符床，并使用接入方私钥对请求参数进行加签，并将加签的值存入请求参数sign中*/
        //6.1 排序生成拼接字符串
        List<String> keys = new ArrayList<String>(reqMap.keySet());
        Collections.sort(keys);
        StringBuilder sb1 = new StringBuilder();
        for (String k : keys) {
            if ("sign".equals(k)) {
                continue;
            }
            sb1.append(k).append("=");
            sb1.append(reqMap.get(k));
            sb1.append("&");
        }
        if (sb1.length() > 0) {
            sb1.setLength(sb1.length() - 1);
        }
        //6.2使用接入方私钥对排序的请求参数加签，并存放到请求参数里面.privateFilePath:私钥地址，prvatePassword:私钥密钥
        String sign= RSA256Util.sign(sb1.toString(),MERC_PRIVATE_FILE,MERC_PRIVATE_FILE_PASSWORD);
        reqMap.put("sign",sign );

        /** 7、发送http请求获取返回结果，请求地址以文档为准*/
        try {
            //该文件上传接口必须传文件名称
            String result = HttpRequestUtil.sendPostFileAndName(HTTP_URL, reqMap, file,file.getName());
            byte[] res = Base64.decodeBase64(result);
            Map<String, String> resMap = (Map<String, String>) JSONObject.parse(new String(res, "UTF-8"));
            System.out.println("http请求返回的结果为:" + JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if(StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = SignUtil.getSignDataStr1(resMap).getBytes("UTF-8");
                boolean validateSignResult= RSA256Util.validateSign(YS_PUBLIC_CER_PATH,Base64.decodeBase64(resMap.get("sign")),srcData);
                if(!validateSignResult){
                    System.out.println("验签失败");
                    throw new Exception("验签失败");
                }
            }else{
                throw new Exception("验签失败,未返回加签信息,可能是银盛未配置发起方或者发起方证书类型配置有误,返回结果提示为:{}"+resMap.get("msg"));
            }

            /** 9、针对自己的业务，根据返回的结果的code、subCode、businessData 做接入方的业务处理*/


            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            if (StringUtils.isNotBlank(resMap.get("businessData"))) {
                byte[] data_ = Base64.decodeBase64(resMap.get("businessData"));
                byte[] data = AESUtil.decrypt(data_, ByteUtil.hexStringToBytes(key));
                resMap.put("businessData", new String(data, "UTF-8"));
                System.out.println("解密后的业务参数:" + new String(data, "UTF-8"));
            }
            System.out.println("解密后的完整参数为:" + JSONObject.toJSONString(resMap));
        } catch (Exception e) {
            System.out.println("图片上传demo失败:" + e);
        }
    }

    /**
     * 支付宝实名认证申请
     */
    public static void aliAuthSubmit() throws Exception {
        //请求接口
        String HTTP_URL = HTTP_NET + "/openapi/pregate/alipay/submitAuthMessages";

        /** 1、封装请求参数，bizContent（业务参数，需要加密）和check（需要生成密钥并加密）后面设置值*/
        Map<String,String> reqMap = new HashMap<String,String>();
        //接口方法名，根据接口文档取值
        reqMap.put("method", "pregate.alipay.submitAuthMessages");
        //请求时间
        reqMap.put("timeStamp",getCurrentDateTime("yyyy-MM-dd HH:mm:dd"));
        //固定utf-8
        reqMap.put("charset","utf-8");
        //请求流水号
        reqMap.put("reqId",String.valueOf(System.currentTimeMillis()));
        //发起方商户号，服务商在银盛给自己开设的商户号，即可当作发起方商户号，由银盛生成并下发。 注意：不同于子商户号，服务商发展的商户即为子商户号
        reqMap.put("certId", CERT_ID);
        //版本号，默认1.0，按接口文档来
        reqMap.put("version","1.0");

        /** 2、生成对业务参数加密的密钥*/
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
        }
        String key = ByteUtil.toHexString(sb.toString());

        /** 3、使用银盛公钥对密钥key进行加密，得到加密的key并设置到请求参数check中。publicFilePath为存放银盛公钥的地址*/
        byte[] byte1= RSA256Util.encrypt(YS_PUBLIC_CER_PATH, ByteUtil.hexStringToBytes(key));
        String check = Base64.encodeBase64String(byte1);
        //加密后的密钥
        reqMap.put("check", check);

        /** 4、封装业务参数,具体参数见文档，这里只是举例子*/
        Map<String,Object> bizContentMap = new HashMap<>();
        bizContentMap.put("mercId","QRY220624529882");
        bizContentMap.put("mercName","义乌市鑫光饰品商行");
        bizContentMap.put("contactCorpId","630102198706033683");
        bizContentMap.put("contactsTel","18010201100");
        bizContentMap.put("idValidDateBegin","2022-01-01");
        bizContentMap.put("idValidDateEnd","2032-01-01");
        bizContentMap.put("merContactType","65");
        bizContentMap.put("idTypeCd","00");
        bizContentMap.put("idFrontImg","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("idBackImg","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("busAutLetterImg","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("contDateBegin","2022-01-01");
        bizContentMap.put("contDateEnd","2032-01-01");
        bizContentMap.put("idHolderType","LEGAL");
        bizContentMap.put("busLincenceBegin","2022-01-01");
        bizContentMap.put("busLincenceEnd","2032-01-01");
        bizContentMap.put("managementType","00");
        bizContentMap.put("storeName","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("shopPhoto","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("storeEnvirPhoto","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("linencePhoto","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("indentityPhoto","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("protocolPhoto","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("cocc","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("sfzbackphoto","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("sfzfrontphoto","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("grantAuth","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("idImgHand","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("bankCardImg","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("bdShopPhoto","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("bdPosterPhoto","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("wxPlatform","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("unitPhoto","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("bookType","CERTIFICATE_TYPE_2388");
        bizContentMap.put("hotLine","4008008820");
        bizContentMap.put("financeType","BANK_AGENT");
        List<String> financeLicensePics = new ArrayList<>();
        financeLicensePics.add("group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        bizContentMap.put("financeLicensePics",financeLicensePics);

        //经营许可证列表
        List<Map<String,Object>> specialOperations = new ArrayList<>();
        Map<String,Object> temp = new HashMap<>();
        temp.put("categoryId","mock");
        List<String> operationCopyList = new ArrayList<>();
        operationCopyList.add("mock");
        temp.put("operationCopyList",operationCopyList);
        specialOperations.add(temp);
        bizContentMap.put("specialOperations",specialOperations);

        //受益人
        List<Map<String,String>> beneficiarys = new ArrayList<>();
        Map<String,String> beneficiary = new HashMap<>();
        beneficiary.put("uboIdType","00");
        beneficiary.put("uboIdCardCopy","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        beneficiary.put("uboIdCardNational","group1,M00/26/0D/CtUiIl_Yg_-AcTmgAAU2krJ8NgE60.jpeg");
        beneficiary.put("uboName","张撒娇");
        beneficiary.put("uboIdNumber","630102198706033683");
        beneficiary.put("address","深圳市嘻嘻嘻大道01号");
        beneficiary.put("uboIdCardValidDateBegin","2022-01-01");
        beneficiary.put("uboIdCardValidDateEnd","2032-01-01");
        beneficiarys.add(beneficiary);
        bizContentMap.put("beneficiarys",beneficiarys);

        JSONObject bizJSONObj = JSONObject.parseObject(JSON.toJSONString(bizContentMap));

        /** 5、使用生成的密钥key对业务参数进行加密，并将加密后的业务参数放入请求参数bizContent中*/
        byte[] bte= AESUtil.encrypt(JSONObject.toJSONBytes(bizJSONObj, SerializerFeature.WriteNullStringAsEmpty), ByteUtil.hexStringToBytes(key));
        String msgBizContent = Base64.encodeBase64String(bte);
        reqMap.put("bizContent", msgBizContent);

        /** 6、将请求参数进行sort排序，生成拼接的字符床，并使用接入方私钥对请求参数进行加签，并将加签的值存入请求参数sign中*/
        //6.1 排序生成拼接字符串
        List<String> keys = new ArrayList<String>(reqMap.keySet());
        Collections.sort(keys);
        StringBuilder sb1 = new StringBuilder();
        for(String k : keys){
            if("sign".equals(k)) {
                continue;
            }
            sb1.append(k).append("=");
            sb1.append(reqMap.get(k));
            sb1.append("&");
        }
        if(sb1.length() > 0) {
            sb1.setLength(sb1.length() - 1);
        }
        //6.2使用接入方私钥对排序的请求参数加签，并存放到请求参数里面.privateFilePath:私钥地址，prvatePassword:私钥密钥
        String sign= RSA256Util.sign(sb1.toString(),MERC_PRIVATE_FILE,MERC_PRIVATE_FILE_PASSWORD);
        reqMap.put("sign",sign );

        /** 7、发送http请求获取返回结果，请求地址以文档为准*/
        try {
            String result = HttpRequestUtil.getDoPostResponse(HTTP_URL, reqMap, "UTF-8", null, 20*1000);
            byte[] res = Base64.decodeBase64(result);
            Map<String, String> resMap = (Map<String, String>) JSONObject.parse(new String(res,"UTF-8"));
            System.out.println("http请求返回的结果为:"+JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if(StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = SignUtil.getSignDataStr1(resMap).getBytes("UTF-8");
                boolean validateSignResult= RSA256Util.validateSign(YS_PUBLIC_CER_PATH,Base64.decodeBase64(resMap.get("sign")),srcData);
                if(!validateSignResult){
                    System.out.println("验签失败");
                    throw new Exception("验签失败");
                }
            }else{
                throw new Exception("验签失败,未返回加签信息,可能是银盛未配置发起方或者发起方证书类型配置有误,返回结果提示为:{}"+resMap.get("msg"));
            }

            /** 9、针对自己的业务，根据返回的结果的code 和 subCode 做接入方的业务处理*/


            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            if(StringUtils.isNotBlank(resMap.get("businessData"))) {
                byte[] data_ = Base64.decodeBase64(resMap.get("businessData"));
                byte[] data = AESUtil.decrypt(data_,ByteUtil.hexStringToBytes(key));
                resMap.put("businessData", new String(data,"UTF-8"));
                System.out.println("解密后的业务参数:"+new String(data,"UTF-8"));
            }
            System.out.println("解密后的完整参数为:"+JSONObject.toJSONString(resMap));
        } catch (Exception e) {
            System.out.println("商户入网申请失败:"+e.getMessage());
        }
    }


    /**
     * 撤销
     */
    public static void cancelAuthMessages() throws Exception {
        //请求接口
        String HTTP_URL = HTTP_NET + "/openapi/pregate/alipay/cancelAuthMessages";

        /** 1、封装请求参数，bizContent（业务参数，需要加密）和check（需要生成密钥并加密）后面设置值*/
        Map<String,String> reqMap = new HashMap<String,String>();
        //接口方法名，根据接口文档取值
        reqMap.put("method", "pregate.alipay.cancelAuthMessages");
        //请求时间
        reqMap.put("timeStamp",getCurrentDateTime("yyyy-MM-dd HH:mm:dd"));
        //固定utf-8
        reqMap.put("charset","utf-8");
        //请求流水号
        reqMap.put("reqId",String.valueOf(System.currentTimeMillis()));
        //发起方商户号，服务商在银盛给自己开设的商户号，即可当作发起方商户号，由银盛生成并下发。 注意：不同于子商户号，服务商发展的商户即为子商户号
        reqMap.put("certId", CERT_ID);
        //版本号，默认1.0，按接口文档来
        reqMap.put("version","1.0");

        /** 2、生成对业务参数加密的密钥*/
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
        }
        String key = ByteUtil.toHexString(sb.toString());

        /** 3、使用银盛公钥对密钥key进行加密，得到加密的key并设置到请求参数check中。publicFilePath为存放银盛公钥的地址*/
        byte[] byte1= RSA256Util.encrypt(YS_PUBLIC_CER_PATH, ByteUtil.hexStringToBytes(key));
        String check = Base64.encodeBase64String(byte1);
        //加密后的密钥
        reqMap.put("check", check);

        /** 4、封装业务参数,具体参数见文档，这里只是举例子*/
        Map<String,Object> bizContentMap = new HashMap<>();
        bizContentMap.put("mercId","QRY220624529882");
        bizContentMap.put("sendChannelApplyNo","A0902144853318833622");

        JSONObject bizJSONObj = JSONObject.parseObject(JSON.toJSONString(bizContentMap));

        /** 5、使用生成的密钥key对业务参数进行加密，并将加密后的业务参数放入请求参数bizContent中*/
        byte[] bte= AESUtil.encrypt(JSONObject.toJSONBytes(bizJSONObj, SerializerFeature.WriteNullStringAsEmpty), ByteUtil.hexStringToBytes(key));
        String msgBizContent = Base64.encodeBase64String(bte);
        reqMap.put("bizContent", msgBizContent);

        /** 6、将请求参数进行sort排序，生成拼接的字符床，并使用接入方私钥对请求参数进行加签，并将加签的值存入请求参数sign中*/
        //6.1 排序生成拼接字符串
        List<String> keys = new ArrayList<String>(reqMap.keySet());
        Collections.sort(keys);
        StringBuilder sb1 = new StringBuilder();
        for(String k : keys){
            if("sign".equals(k)) {
                continue;
            }
            sb1.append(k).append("=");
            sb1.append(reqMap.get(k));
            sb1.append("&");
        }
        if(sb1.length() > 0) {
            sb1.setLength(sb1.length() - 1);
        }
        //6.2使用接入方私钥对排序的请求参数加签，并存放到请求参数里面.privateFilePath:私钥地址，prvatePassword:私钥密钥
        String sign= RSA256Util.sign(sb1.toString(),MERC_PRIVATE_FILE,MERC_PRIVATE_FILE_PASSWORD);
        reqMap.put("sign",sign );

        /** 7、发送http请求获取返回结果，请求地址以文档为准*/
        try {
            String result = HttpRequestUtil.getDoPostResponse(HTTP_URL, reqMap, "UTF-8", null, 20*1000);
            byte[] res = Base64.decodeBase64(result);
            Map<String, String> resMap = (Map<String, String>) JSONObject.parse(new String(res,"UTF-8"));
            System.out.println("http请求返回的结果为:"+JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if(StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = SignUtil.getSignDataStr1(resMap).getBytes("UTF-8");
                boolean validateSignResult= RSA256Util.validateSign(YS_PUBLIC_CER_PATH,Base64.decodeBase64(resMap.get("sign")),srcData);
                if(!validateSignResult){
                    System.out.println("验签失败");
                    throw new Exception("验签失败");
                }
            }else{
                throw new Exception("验签失败,未返回加签信息,可能是银盛未配置发起方或者发起方证书类型配置有误,返回结果提示为:{}"+resMap.get("msg"));
            }

            /** 9、针对自己的业务，根据返回的结果的code 和 subCode 做接入方的业务处理*/


            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            if(StringUtils.isNotBlank(resMap.get("businessData"))) {
                byte[] data_ = Base64.decodeBase64(resMap.get("businessData"));
                byte[] data = AESUtil.decrypt(data_,ByteUtil.hexStringToBytes(key));
                resMap.put("businessData", new String(data,"UTF-8"));
                System.out.println("解密后的业务参数:"+new String(data,"UTF-8"));
            }
            System.out.println("解密后的完整参数为:"+JSONObject.toJSONString(resMap));
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 支付宝实名认证申请单状态查询
     */
    public static void getAuthMessagesByApplyNo() throws Exception {
        //请求接口
        String HTTP_URL = HTTP_NET + "/openapi/pregate/alipay/getAuthMessagesByApplyNo";

        /** 1、封装请求参数，bizContent（业务参数，需要加密）和check（需要生成密钥并加密）后面设置值*/
        Map<String,String> reqMap = new HashMap<String,String>();
        //接口方法名，根据接口文档取值
        reqMap.put("method", "pregate.alipay.getAuthMessagesByApplyNo");
        //请求时间
        reqMap.put("timeStamp",getCurrentDateTime("yyyy-MM-dd HH:mm:dd"));
        //固定utf-8
        reqMap.put("charset","utf-8");
        //请求流水号
        reqMap.put("reqId",String.valueOf(System.currentTimeMillis()));
        //发起方商户号，服务商在银盛给自己开设的商户号，即可当作发起方商户号，由银盛生成并下发。 注意：不同于子商户号，服务商发展的商户即为子商户号
        reqMap.put("certId", CERT_ID);
        //版本号，默认1.0，按接口文档来
        reqMap.put("version","1.0");

        /** 2、生成对业务参数加密的密钥*/
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
        }
        String key = ByteUtil.toHexString(sb.toString());

        /** 3、使用银盛公钥对密钥key进行加密，得到加密的key并设置到请求参数check中。publicFilePath为存放银盛公钥的地址*/
        byte[] byte1= RSA256Util.encrypt(YS_PUBLIC_CER_PATH, ByteUtil.hexStringToBytes(key));
        String check = Base64.encodeBase64String(byte1);
        //加密后的密钥
        reqMap.put("check", check);

        /** 4、封装业务参数,具体参数见文档，这里只是举例子*/
        Map<String,Object> bizContentMap = new HashMap<>();
        bizContentMap.put("mercId","QRY220624529882");
        bizContentMap.put("sendChannelApplyNo","A0902144853318833622");
        JSONObject bizJSONObj = JSONObject.parseObject(JSON.toJSONString(bizContentMap));

        /** 5、使用生成的密钥key对业务参数进行加密，并将加密后的业务参数放入请求参数bizContent中*/
        byte[] bte= AESUtil.encrypt(JSONObject.toJSONBytes(bizJSONObj, SerializerFeature.WriteNullStringAsEmpty), ByteUtil.hexStringToBytes(key));
        String msgBizContent = Base64.encodeBase64String(bte);
        reqMap.put("bizContent", msgBizContent);

        /** 6、将请求参数进行sort排序，生成拼接的字符床，并使用接入方私钥对请求参数进行加签，并将加签的值存入请求参数sign中*/
        //6.1 排序生成拼接字符串
        List<String> keys = new ArrayList<String>(reqMap.keySet());
        Collections.sort(keys);
        StringBuilder sb1 = new StringBuilder();
        for(String k : keys){
            if("sign".equals(k)) {
                continue;
            }
            sb1.append(k).append("=");
            sb1.append(reqMap.get(k));
            sb1.append("&");
        }
        if(sb1.length() > 0) {
            sb1.setLength(sb1.length() - 1);
        }
        //6.2使用接入方私钥对排序的请求参数加签，并存放到请求参数里面.privateFilePath:私钥地址，prvatePassword:私钥密钥
        String sign= RSA256Util.sign(sb1.toString(),MERC_PRIVATE_FILE,MERC_PRIVATE_FILE_PASSWORD);
        reqMap.put("sign",sign );

        /** 7、发送http请求获取返回结果，请求地址以文档为准*/
        try {
            String result = HttpRequestUtil.getDoPostResponse(HTTP_URL, reqMap, "UTF-8", null, 20*1000);
            byte[] res = Base64.decodeBase64(result);
            Map<String, String> resMap = (Map<String, String>) JSONObject.parse(new String(res,"UTF-8"));
            System.out.println("http请求返回的结果为:"+JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if(StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = SignUtil.getSignDataStr1(resMap).getBytes("UTF-8");
                boolean validateSignResult= RSA256Util.validateSign(YS_PUBLIC_CER_PATH,Base64.decodeBase64(resMap.get("sign")),srcData);
                if(!validateSignResult){
                    System.out.println("验签失败");
                    throw new Exception("验签失败");
                }
            }else{
                throw new Exception("验签失败,未返回加签信息,可能是银盛未配置发起方或者发起方证书类型配置有误,返回结果提示为:{}"+resMap.get("msg"));
            }

            /** 9、针对自己的业务，根据返回的结果的code 和 subCode 做接入方的业务处理*/


            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            if(StringUtils.isNotBlank(resMap.get("businessData"))) {
                byte[] data_ = Base64.decodeBase64(resMap.get("businessData"));
                byte[] data = AESUtil.decrypt(data_,ByteUtil.hexStringToBytes(key));
                resMap.put("businessData", new String(data,"UTF-8"));
                System.out.println("解密后的业务参数:"+new String(data,"UTF-8"));
            }
            System.out.println("解密后的完整参数为:"+JSONObject.toJSONString(resMap));
        } catch (Exception e) {
            System.out.println("商户入网申请失败:"+e.getMessage());
        }
    }

    /**
     * 银行卡号查询卡bin
     */
    public static void getAuthState() throws Exception {
        //请求接口
        String HTTP_URL = HTTP_NET + "/openapi/pregate/alipay/getAuthState";

        /** 1、封装请求参数，bizContent（业务参数，需要加密）和check（需要生成密钥并加密）后面设置值*/
        Map<String,String> reqMap = new HashMap<String,String>();
        //接口方法名，根据接口文档取值
        reqMap.put("method", "pregate.alipay.getAuthState");
        //请求时间
        reqMap.put("timeStamp",getCurrentDateTime("yyyy-MM-dd HH:mm:dd"));
        //固定utf-8
        reqMap.put("charset","utf-8");
        //请求流水号
        reqMap.put("reqId",String.valueOf(System.currentTimeMillis()));
        //发起方商户号，服务商在银盛给自己开设的商户号，即可当作发起方商户号，由银盛生成并下发。 注意：不同于子商户号，服务商发展的商户即为子商户号
        reqMap.put("certId", CERT_ID);
        //版本号，默认1.0，按接口文档来
        reqMap.put("version","1.0");

        /** 2、生成对业务参数加密的密钥*/
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
        }
        String key = ByteUtil.toHexString(sb.toString());

        /** 3、使用银盛公钥对密钥key进行加密，得到加密的key并设置到请求参数check中。publicFilePath为存放银盛公钥的地址*/
        byte[] byte1= RSA256Util.encrypt(YS_PUBLIC_CER_PATH, ByteUtil.hexStringToBytes(key));
        String check = Base64.encodeBase64String(byte1);
        //加密后的密钥
        reqMap.put("check", check);

        /** 4、封装业务参数,具体参数见文档，这里只是举例子*/
        Map<String,Object> bizContentMap = new HashMap<>();
        //mcc码
        bizContentMap.put("mercId","QRY220624529882");

        JSONObject bizJSONObj = JSONObject.parseObject(JSON.toJSONString(bizContentMap));

        /** 5、使用生成的密钥key对业务参数进行加密，并将加密后的业务参数放入请求参数bizContent中*/
        byte[] bte= AESUtil.encrypt(JSONObject.toJSONBytes(bizJSONObj, SerializerFeature.WriteNullStringAsEmpty), ByteUtil.hexStringToBytes(key));
        String msgBizContent = Base64.encodeBase64String(bte);
        reqMap.put("bizContent", msgBizContent);

        /** 6、将请求参数进行sort排序，生成拼接的字符床，并使用接入方私钥对请求参数进行加签，并将加签的值存入请求参数sign中*/
        //6.1 排序生成拼接字符串
        List<String> keys = new ArrayList<String>(reqMap.keySet());
        Collections.sort(keys);
        StringBuilder sb1 = new StringBuilder();
        for(String k : keys){
            if("sign".equals(k)) {
                continue;
            }
            sb1.append(k).append("=");
            sb1.append(reqMap.get(k));
            sb1.append("&");
        }
        if(sb1.length() > 0) {
            sb1.setLength(sb1.length() - 1);
        }
        //6.2使用接入方私钥对排序的请求参数加签，并存放到请求参数里面.privateFilePath:私钥地址，prvatePassword:私钥密钥
        String sign= RSA256Util.sign(sb1.toString(),MERC_PRIVATE_FILE,MERC_PRIVATE_FILE_PASSWORD);
        reqMap.put("sign",sign );

        /** 7、发送http请求获取返回结果，请求地址以文档为准*/
        try {
            String result = HttpRequestUtil.getDoPostResponse(HTTP_URL, reqMap, "UTF-8", null, 20*1000);
            byte[] res = Base64.decodeBase64(result);
            Map<String, String> resMap = (Map<String, String>) JSONObject.parse(new String(res,"UTF-8"));
            System.out.println("http请求返回的结果为:"+JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if(StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = SignUtil.getSignDataStr1(resMap).getBytes("UTF-8");
                boolean validateSignResult= RSA256Util.validateSign(YS_PUBLIC_CER_PATH,Base64.decodeBase64(resMap.get("sign")),srcData);
                if(!validateSignResult){
                    System.out.println("验签失败");
                    throw new Exception("验签失败");
                }
            }else{
                throw new Exception("验签失败,未返回加签信息,可能是银盛未配置发起方或者发起方证书类型配置有误,返回结果提示为:{}"+resMap.get("msg"));
            }

            /** 9、针对自己的业务，根据返回的结果的code 和 subCode 做接入方的业务处理*/


            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            if(StringUtils.isNotBlank(resMap.get("businessData"))) {
                byte[] data_ = Base64.decodeBase64(resMap.get("businessData"));
                byte[] data = AESUtil.decrypt(data_,ByteUtil.hexStringToBytes(key));
                resMap.put("businessData", new String(data,"UTF-8"));
                System.out.println("解密后的业务参数:"+new String(data,"UTF-8"));
            }
            System.out.println("解密后的完整参数为:"+JSONObject.toJSONString(resMap));
        } catch (Exception e) {
            System.out.println("商户入网申请失败:"+e.getMessage());
        }
    }

    /**
     * 格式化当前日期时间字符串
     * @return
     */
    private static  String getCurrentDateTime(String pattern){
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(new Date());
    }
}
